package com.fm8088.app.ext

import android.widget.EditText
import android.widget.TextView


/** 任何类型转浮点型或0 */
fun Any?.toFloatOrZero(): Float {
    if (this is Number) {
        return toFloat()
    }
    return this?.toString()?.toFloatOrNull() ?: 0f
}

/** 保持两位小数 */
fun Any?.keep2bitFloat(): String {
    return "%.2f".format(this.toFloatOrZero())
}

/** 保持一位小数 */
fun Any?.keep1bitFloat(): String {
    return "%.1f".format(this.toFloatOrZero())
}

/** 去除小数点（任何类型尝试转换成整形） */
fun Any?.removeDecimal(): String {
    return when (this) {
        is Number -> this.toInt().toString()
        else -> this.toFloatOrZero().toInt().toString()
    }
}

/** 保持两位小说或0 */
fun Any?.keep2bitFloatOrZero(): String {
    val value = this.toFloatOrZero()
    if (value == 0.0f) {
        return "0"
    }
    return "%.2f".format(value)
}


fun CharSequence?.isNotNullAndEmpty(): Boolean =
    this?.isNotEmpty() ?: false


fun EditText.intValue(range: IntRange? = null): Int? {
    val toInt = this.text.toString().trim().toIntOrNull()

    if (toInt != null && range != null && toInt !in range) {
        return null
    }
    return toInt
}

fun TextView.floatOrNull(): Float? {
    return this.text.toString().trim().toFloatOrNull()
}

fun TextView.floatOrZero(): Float {
    return this.text.toString().trim().toFloatOrNull() ?: 0.0f
}


fun EditText.setValue(value: Any?): Unit {
    this.setText(value?.toString())
}


val TextView.string get() = this.text.toString()

